import Taro from '@tarojs/taro'
import { create } from 'dva-core';
import immer from 'dva-immer';

export function createDva(opt) {
  // opt.onAction = [createLogger()];
  let store = {};
  const app = create(opt);
  // app.use(createLoading({}));
  app.use(immer());

  if (!global.registered) opt.models.forEach(model => app.model(model));
  global.registered = true;
  app.start();

  store = app._store;
  app.store = app._store
  app.getStore = () => store;

  app.dispatch = app._store.dispatch;
  app.update = update

  if (window) {
    window.g_app = app;
  }
  return app;
}

const update = () => {
  if (process.env.TARO_ENV === 'weapp') {
    const updateManager = Taro.getUpdateManager();
    Taro.getUpdateManager().onUpdateReady(function () {
      Taro.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
  }
}
